const app = getApp();
var config = app.globalData.config;
const http = require('../../utils/http.js');
const jhmd5 = require('../course_pay/md5.js');
const jhpay = require('../course_pay/pay.js');
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		mode: '', // add,edit 添加或者编辑
		student_list_active_id: '', //选中的学生id
		student_active_index: '', //选择的学生列表下标
		student_list: [
			// {
			// 	id: 22,
			// 	student_name: '陶渊明',
			// 	sex: 1,
			// 	birthday: '2010-08-08',
			// 	school_id: 1,
			// 	school_name: '隆安中心小学',
			// 	grade_id: 3,
			// 	grade_name: '三年级',
			// 	class_id: 6,
			// 	class_name: '一班'
			// },
			// {
			// 	id: 33,
			// 	student_name: '王昭君',
			// 	sex: 0,
			// 	birthday: '2010-08-08',
			// 	school_id: 1,
			// 	school_name: '隆安中心小学',
			// 	grade_id: 3,
			// 	grade_name: '三年级',
			// 	class_id: 6,
			// 	class_name: '一班'
			// }
		],
		sex_list: [{
				id: 1,
				sex_name: '男'
			},
			{
				id: 2,
				sex_name: '女'
			}
		],
		school_list: [{
				id: 1,
				name: '隆安中心小学'
			},
			{
				id: 2,
				name: '周宁中心小学'
			}
		],
		parentage_list:[{
					id: 0,
					parentage_name: '爸爸'
				},
				{
					id: 1,
					parentage_name: '妈妈'
				}
		],//亲子关系
		grade_list: [{
				id: 3,
				grade_name: '一年级'
			},
			{
				id: 4,
				grade_name: '二年级'
			},
			{
				id: 5,
				grade_name: '三年级'
			}
		],
		class_list: [{
				id: 6,
				class_name: '一班'
			},
			{
				id: 7,
				class_name: '二班'
			}
		],
		add_item: {
			parentage_index:'',
			student_name: '',
			sex_index: '',
			birthday: '',
			school_index: '',
			grade_index: '',
			class_index: ''
		},
		edit_item: {},
		schoolIdDauflt: 0,
		initFlag : false,//初始化参数
		isShow:false	,//模态框参数
		sname:'xxx'	,//模态框参数-选中学生姓名
		order_num:"",//订单编号
		bank_mac:"",//银行mac
		no_multipleclick:false,//防止多次点击提交订单
	},
	onReady: function() {
		if (!app.login()) {
			return;
		}
	},
	onLoad(options) {
		var that = this;
		this.classId = options.id; //前面传的 班级id【课程id】
		this.cname = options.cname;
		this.tuition = options.tuition;
		this.setData({
			'cname': that.cname,
			'tuition': that.tuition
		})

		this.getSchoolList(); //选项框-获取学校-班级
		this.getGradeList(); //选项框-获取年级
		this.getStudentList(); //学生列表初始化
		
		this.getParentageList();	//获取【亲子关系】
	},
	getStudentList() { //获取学生列表
		var that = this;
		http.httpPost(config.get_student_list, {}, function(e) {
			that.student_list = e.data;
			console.log(that.student_list )
			if(that.data.initFlag==false && e.data.length>0){
				that.data.initFlag = true;
				that.student_list_active_id = e.data[0].id;	//默认选择第一个孩子
				that.student_active_index = 0;
			
				that.setData({
					'student_list': e.data,
					'initFlag': true,
					'student_list_active_id': e.data[0].id,
					'student_active_index': 0,
					'mode': 'edit',
					'edit_item': e.data[0]
				})
			}
			
			
		});
	},
	getParentageList(){//获取亲子关系
		var that = this;
		http.httpPost(config.get_parentage_list, {}, function(e) {
			that.parentage_list = e.data;
			
			that.setData({
				'parentage_list': e.data
			})
			
		});
	},
	//更改亲子关系
	parentageChange: function(e) {
		let add_item = this.data.add_item;
		add_item.parentage_index = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改学生姓名
	studentnameChange: function(e) {
		let add_item = this.data.add_item;
		add_item.student_name = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改学生性别
	sexChange: function(e) {
		let add_item = this.data.add_item;
		add_item.sex_index = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	//更改出生日期
	birthdayChange: function(e) {
		let add_item = this.data.add_item;
		add_item.birthday = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},

	//更改学校
	schoolChange: function(e) {
		let add_item = this.data.add_item;
		add_item.school_index = e.detail.value;
		this.setData({
			add_item: add_item
		})

		//改变班级列表
		this.schoolIdDauflt = this.school_list[e.detail.value].id;
		this.getClassList();
	},
	getSchoolList() { //获取【校园列表】
		var that = this;
		http.httpPost(config.get_school_list, {
			showStatus: true
		}, function(e) {
			that.school_list = e.data;
			that.setData({
				'school_list': e.data
			})
			//
			if (e.data.length > 0) {
				that.schoolIdDauflt = e.data[0].id;
				that.getClassList()
			}

		});

	},
	getClassList(_id = null) { //获取【报名课程】
		var that = this;
		http.httpPost(config.get_studentclasses_list, {
			school_id: that.schoolIdDauflt
		}, function(e) {
			that.class_list = e.data;

			that.setData({
				'class_list': e.data
			})
		});
	},
	//更改年级
	gradeChange: function(e) {
		let add_item = this.data.add_item;
		add_item.grade_index = e.detail.value;
		this.setData({
			add_item: add_item
		})
	},
	getGradeList() { //获取【年级】
		var that = this;
		http.httpPost(config.get_grade_list, {
			showStatus: true
		}, function(e) {
			that.grade_list = e.data;

			that.setData({
				'grade_list': e.data
			})

		});
	},
	//更改班级
	classChange: function(e) {
		let add_item = this.data.add_item;
		add_item.class_index = e.detail.value;
		this.setData({
			add_item: add_item
		})

	},

	//添加学生
	addStudent: function(e) {
		let add_item = {};
		if (this.data.add_item.parentage_index == '') {
			wx.showToast({
				title: '请选择亲子关系',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.parentage_name = this.data.parentage_list[this.data.add_item.parentage_index].parentage_name;
		
		if (this.data.add_item.student_name == '') {
			wx.showToast({
				title: '请输入学生姓名',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.student_name = this.data.add_item.student_name;

		if (this.data.add_item.sex_index == '') {
			wx.showToast({
				title: '请选择学生性别',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.sex = this.data.sex_list[this.data.add_item.sex_index].id;

		if (this.data.add_item.birthday == '') {
			wx.showToast({
				title: '请选择出生日期',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.birthday = this.data.add_item.birthday;

		if (this.data.add_item.school_index == '') {
			wx.showToast({
				title: '请选择学校',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.school_id = this.data.school_list[this.data.add_item.school_index].id;
		add_item.school_name = this.data.grade_list[this.data.add_item.school_index].name;

		if (this.data.add_item.grade_index == '') {
			wx.showToast({
				title: '请选择年级',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.grade_id = this.data.grade_list[this.data.add_item.grade_index].id;
		add_item.grade_name = this.data.grade_list[this.data.add_item.grade_index].grade_name;

		if (this.data.add_item.class_index == '') {
			wx.showToast({
				title: '请选择班级',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}
		add_item.class_id = this.data.class_list[this.data.add_item.class_index].id;
		add_item.class_name = this.data.class_list[this.data.add_item.class_index].class_name;

		let student_list = this.data.student_list;
		// student_list.push(add_item);

		//添加孩子信息
		var that = this;
		http.httpPost(config.get_add_childdata, {
			parentage:that.data.add_item.parentage_index,
			studentname: that.data.add_item.student_name,
			school_id: that.data.school_list[that.data.add_item.school_index].id,
			sex: that.data.sex_list[that.data.add_item.sex_index].id,
			birthtime: that.data.add_item.birthday,
			grade_id: that.data.grade_list[that.data.add_item.grade_index].id,
			class_id: that.data.class_list[that.data.add_item.class_index].id,
		}, function(e) {
			wx.showToast({
				title: e.msg,
				icon: 'none',
				duration: 1000,
				mask: true
			});
			if (e.code == 1) {
				add_item.id = e.data;
				student_list.push(add_item);
			}
			that.setData({
				'student_list': student_list,
				'add_item': {
					parentage_index:'',
					student_name: '',
					sex_index: '',
					birthday: '',
					school_index: '',
					grade_index: '',
					class_index: ''
				}
			})
		});

	},
	//激活报名学生
	selectStudent: function(e) {
		this.student_list_active_id = e.currentTarget.dataset.id;
		this.student_active_index = e.currentTarget.dataset.key;
		this.setData({
			"student_list_active_id": e.currentTarget.dataset.id,
			"student_active_index": e.currentTarget.dataset.key,
			mode: 'edit',
			edit_item: this.data.student_list[e.currentTarget.dataset.key]
		})
	},
	//进入添加模式
	studentModeAdd: function(e) {
		this.setData({
			mode: 'add'
		})
	},
	//删除学生
	delete_item: function(e) {
		var that = this;
		let student_list = this.data.student_list;
		student_list.forEach(function(item, index) {
			if (item.id == that.data.edit_item.id) {
				http.httpPost(config.del_student, {
					student_id: item.id
				}, function(e) {
					student_list.splice(index, 1);
					wx.showToast({
						title: '删除成功',
						icon: 'none',
						duration: 1000,
						mask: true
					})
					that.setData({
						student_list: student_list,
						mode: ''
					})

				});

				return;
			}
		});
	},
	isWxPayBtn(){
		if (this.student_list_active_id == undefined) {
			wx.showToast({
				title: '请选择学生',
				icon: 'none',
				duration: 1000,
				mask: true
			})
			return;
		} else {
			var _isPay = false;
			this.isShow = true;
			this.sname = this.student_list[this.student_active_index].student_name;
			this.setData({
				isShow: true,
				sname:this.sname
			})
		
		}
	},
	cancelBtn(){//模态框-取消
		this.isShow = false;
		this.setData({
			isShow: false
		})
	},
	confirmPayBtn(){//模态框-确认支付
		//防止多次点击
		if(this.no_multipleclick){
			wx.showToast({
				title: '请勿多次点击确认',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return;
		}else{
			this.no_multipleclick = true;
			this.setData({
				no_multipleclick: true
			});
		}
		
		//校验人数是否超出
		var that = this;
		http.httpPost(config.checkenrollstudent, {
			curriculum_id: that.classId, //订单类型:1=餐饮订单,2=课程订单
		}, function(e) {
			if(e.data){
				wx.showToast({
					title: '该课程已达到报名上限',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}else{
				that.buildBankParam();
			}
		})
		
	},
	buildBankParam(){//构建参数
		var that = this;
		var user_openid = app.globalData.userInfo.openid;
		var bankUrl = "";
		
		var _timeStamp = "";
		var _nonceStr = "";
		var _package = "";
		var _signType = "";
		var _paySign = "";
		
		http.httpPost(config.get_order_num, {
			etype: 2, //订单类型:1=餐饮订单,2=课程订单
		}, function(e) {
			var order_num = e.data;
			// console.log("order_num:"+order_num);
			//测试fixme 0.01是金额；倒数第二个是时间
			var bank_str = jhpay.make(order_num,that.tuition,"","","","","","",user_openid);
			// console.log(bank_str);
			// var _str = "MERCHANTID=105000582994528&POSID=070424517&BRANCHID=350000000&ORDERID=kc202209011147059891&PAYMENT=0.01&CURCODE=01&TXCODE=530590&REMARK1=&REMARK2=&TYPE=1&PUB=65ad01f50fddeaeaf3d7a35d020111&GATEWAY=0&CLIENTIP=120.78.216.181&REGINFO=&PROINFO=&REFERER=&TRADE_TYPE=MINIPRO&SUB_APPID=wx64c7003a659575d7&SUB_OPENID=ofXpS490isnG7fCuIlM3Hit14A_s";
			var bank_mac = jhmd5.hex_md5(bank_str);
			// console.log(bank_mac);
			
			var bankUrl = "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6"+"&"+bank_str+"&MAC="+bank_mac;
			// console.log(bankUrl);
			
			//调用银行接口 todo
			http.httpGet(bankUrl,{},function(e){
			  console.log(e);
			  var resStatus = e.SUCCESS;
			  if(resStatus=="true"){
				  var PAYURL = e.PAYURL;
				  http.httpGet(PAYURL,{},function(e){
						// console.log(e);
						if(e.SUCCESS=="true"){
							_timeStamp = e.timeStamp;
							_nonceStr = e.nonceStr;
							_package = e.package;
							_signType = e.signType;
							_paySign = e.paySign;
							
							that.order_num = order_num;	//订单编号
							that.setData({
								order_num: order_num,
							});
							
							// that.to_pay(order_num,bank_mac,_str,_timeStamp,_nonceStr,_package,_signType,_paySign);
							that.wxPayBtn(order_num,bank_str,bank_mac,_timeStamp,_nonceStr,_package,_signType,_paySign);
							
						}else{
							wx.showToast({
								title: "支付失败，请稍后再试",
								icon: 'none',
								duration: 1000,
								mask: true
							});
						}
				  })
			  }
			  
			})
			
			
		});
		
	},
	wxPayBtn(order_num,bank_str,bank_mac,_timeStamp,_nonceStr,_package,_signType,_paySign) { //微信支付
		var that = this;
		var _student_id = this.student_list_active_id;
		var _list_index = this.student_active_index;
		var _school_id = this.student_list[_list_index].school_id;
		var _money = this.tuition;
		
		http.httpPost(config.add_enroll, {
			student_id: _student_id,
			school_id: _school_id,
			class_id: that.classId,
			etype: 2, //订单类型:1=餐饮订单,2=课程订单
			status: 0, //状态默认是0；状态:0=未付款,1=已报名
			money: _money,
			order_num:order_num,
			bank_mac:bank_mac,
			bank_str:bank_str
		}, function(e) {
			if (e.code == 0) {
				wx.showToast({
					title: '该课程已达到报名上限',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			} else {
				var rid = e.data;
				that.to_pay(rid,bank_mac,bank_str,_timeStamp,_nonceStr,_package,_signType,_paySign);
			}
		});
	},
	//立即缴费
	to_pay(rid,bank_mac,bank_str,_timeStamp,_nonceStr,_package,_signType,_paySign) {
		// var rid = 1;//记录id
		var that = this;
		wx.request({
			url: config.to_pay,
			method: 'post',
			data: {
				order_id: rid,
				openid: app.globalData.userInfo.openid,
				bank_mac:bank_mac,
				bank_str:bank_str
			},
			success: function(res) {
				let data = res.data;
				console.log(data);
				//调起微信支付
				wx.requestPayment({
					timeStamp: _timeStamp,
					 nonceStr: _nonceStr,
					 package: _package,
					 signType: _signType,
					 paySign: _paySign,
					// timeStamp: data.timeStamp,
					// nonceStr: data.nonceStr,
					// package: data.package,
					// signType: data.signType,
					// paySign: data.paySign,
					success: res => {
						console.log(res)
						console.log("支付成功1")
						//更新状态
						that.updateOrderStatus(rid);
					},
					fail: res => {
						console.log(res)
						console.log("支付失败1")
					}
				})
			}
		})

	},
	updateOrderStatus(rid) {
		http.httpPost(config.update_order_status, {
			order_id: rid
		}, function(e) {
			console.log('更新成功')
			if(e.code){
				wx.showToast({
					title: '支付成功',
					icon: 'none',
					duration: 1000,
					mask: true
				});
				setTimeout(function() {
					wx.redirectTo({
						url: '../../pages/index/index'
					})
				}, 1500);
			}else{
				wx.showToast({
					title: '支付失败',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}

		});
	}


})
